<template>
  <div>
    <table>
      <tbody>
        <tr>
          <td>商品编号</td>
          <td><input type="text" v-model.number="id"></td>
        </tr>
        <tr>
          <td>商品名称</td>
          <td><input type="text" v-model="title"></td>
        </tr>
        <tr>
          <td>商品价格</td>
          <td><input type="text" v-model="price"></td>
        </tr>
        <tr>
          <td>商品数量</td>
          <td><input type="text" v-model.number="quantity"></td>
        </tr>
        <tr>
          <td colspan="2"><button @click="addCart">加入购物车</button></td>
        </tr>
      </tbody>
    </table>
    <table>
      <thead>
        <tr>
          <th>编号</th>
          <th>商品名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>金额</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="book in books" :key="book.id">
          <td>{{ book.id }}</td>
          <td>{{ book.title }}</td>
          <td>{{ book.price }}</td>
          <td>
            <button @click="increment({id: book.id, count: -1})" :disabled="book.count === 0">
              -
            </button>
            {{ book.count }}
            <button @click="increment({id: book.id, count: 1})">+</button>
          </td>
          <td>{{ itemPrice(book.id) }}</td>
          <td><button @click="deleteItem(book.id)">删除</button></td>
        </tr>
      </tbody>
    </table>
    <span>总价：￥{{totalPrice}}</span>
  </div>
</template>

<script>
import {mapMutations, mapState, mapGetters, mapActions} from 'vuex'
export default {
  data(){
    return {
      id: '',
      title: '',
      price: '',
      quantity: 1
    }
  },
  computed: {
    ...mapState('cart', {
      books: 'items'
      //books: state => state.cart.items
    }),
    /*totalPrice(){
      return this.$store.getters['a/b/cartTotalPrice']
    },*/
    ...mapGetters('cart', {
      totalPrice: 'cartTotalPrice',
      itemPrice: 'cartItemPrice'
    })
  },
  methods: {
    /*...mapMutations([
      'pushItemToCart'
    ]),*/
    ...mapMutations('cart', {
      addItemToCart: 'pushItemToCart',
      deleteItem: 'deleteItem',
      increment: 'incrementItemCount'
    }),
    ...mapActions('cart', [
      'addItemToCart'
    ]),
    addCart(){
      //this.$store.commit('pushItemToCart', {
      //this.addItemToCart({
      //this.$store.dispatch('addItemToCart', {
      this.addItemToCart({
        id: this.id,
        title: this.title,
        price: this.price,
        count: this.quantity
      })
      this.id = ''
      this.title = ''
      this.price = ''
      this.quantity = 1
    }
  }
};
</script>

<style scoped>
div {
  width: 800px
}
table {
  border: 1px solid black;
  width: 100%;
  margin-top: 10px;
}

th {
  height: 50px;
}
th,
td {
  border-bottom: 1px solid #ddd;
  text-align: center;
}
span {
  float: right;
}
</style>